package com.util.db;


import java.io.IOException;
import java.io.InputStream;


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import com.util.db.DBSessionGenerator;




public final class DBSessionGenerator {
	
	private static SqlSessionFactory sqlSessionFactory1 = null;
	
	private static SqlSessionFactory sqlSessionFactory2 = null;
	
	private static Logger logger = Logger.getLogger(DBSessionGenerator.class);

	private static void initSqlSessionFactory() throws IOException {
		
		InputStream is = Resources.getResourceAsStream("config/mybatis_config.xml");
		sqlSessionFactory1 = new SqlSessionFactoryBuilder().build(is);
		
		
	}
	
    private static void initSqlSessionFactory(String list) throws IOException {
		
		InputStream is = Resources.getResourceAsStream("config/mybatis_config.xml");
		sqlSessionFactory2 = new SqlSessionFactoryBuilder().build(is,list);
		
		
	}
	
	public static  SqlSession getSqlSession() {
		if (sqlSessionFactory1 == null) {
			try {
				initSqlSessionFactory();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				return null;
			}
		}
		return sqlSessionFactory1.openSession(true);
	}
	
	public static SqlSession getSqlSession(boolean autoCommit) {
		if (sqlSessionFactory1 == null) {
			try {
				initSqlSessionFactory();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				return null;
			}
		}
		return sqlSessionFactory1.openSession(autoCommit);
	}
	
	public static SqlSession getSqlSession(String list,boolean autoCommit) {
		if (sqlSessionFactory2 == null) {
			try {
				initSqlSessionFactory(list);
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				return null;
			}
		}
		return sqlSessionFactory2.openSession(autoCommit);
	}
	public static SqlSession getSqlSession(String list) {
		if (sqlSessionFactory2 == null) {
			try {
				initSqlSessionFactory(list);
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				return null;
			}
		}
		return sqlSessionFactory2.openSession(true);
	}
}